Exceptions | |
---|---|
NameError | This occurs when a variable is not defined, it hasn’t been assigned. |
TypeError | An operation or function is applied to the wrong type. |
ValueError | This occurs an argument that has the right type but an inappropriate value. |
ZeroDivisionError | Occurs when a number is divided by zero. |
IOError | It occurs when Input Output operation fails. |
IndexError | An IndexError is raised when a sequence is referenced which is out of range. |
Exception |
|
try: Statement --------- except exceptionX as e: Statement --------- except exceptionY as e: Statement --------- ... else: statement --------- finally: statement ---------
try: print("start") z=4/2 print(z) except ZeroDivisionError: print("divide by zero") except ValueError: print("Value Error") else: print("No error") finally: print("Always Executed...")
start 2.0 No error Always Executed...
try: print("Start") z=4/0 print(z) except ZeroDivisionError: print("divide by zero") except ValueError: print("Value Error") else: print("No error") finally: print("Always Executed...")
Start divide by zero Always Executed..
def test(): try: print("open file") z=4/0 print(z) finally: print("close file") try: test( ) except ZeroDivisionError: print("divide by zero") except ValueError: print("Value Error") else: print("No error") finally: print("Always Executed...")
open file close file divide by zero Always Executed...
try: age = int(input("Enter age:")) if age<0: raise ValueError else: print("the age is valid") except ValueError: print("The age is not valid")
Enter age: 23 The age is valid Enter age: -25 The age is not valid
class AgeError(Exception): pass try: age = int(input("Enter age:")) if age<0: raise AgeError() else: print("The age is valid") except AgeError: print("The age is not valid")
Enter age: 23 The age is valid Enter age: -25 The age is not valid